package walace.stocktracer;

import java.util.ArrayList;
import java.util.List;

import walace.stocktracer.StockDatabase;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;


public class StockTracerWidgetProvider extends AppWidgetProvider {

	public static final String INTENT_ITEM_WIDGET_ID = "item_widget_id";
	public static final String INTENT_ITEM_SYMB = "item_sym";
	public static final String INTENT_ITEM_NAME = "item_name";
	public static final String INTENT_ITEM_PRICE = "item_price";
	public static final String INTENT_ITEM_CHANGE_PERCENT = "item_change_percent";
	public static final String INTENT_ITEM_CHANGE = "item_change";
	
	private static final String TAG = "StockTracerWidgetProvider";

	
	
	
    private static Thread mThread = null;    
    private volatile static boolean mThreadRun = false;
	
    public static EasyStockWidgetConfig mConfig = new EasyStockWidgetConfig();
    
	//private static boolean mWidgetEnabled = false;	
	private static List<StockItem> mItemsList = mConfig.mItemsList;
	//private static int update_period_second = 3;
	
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {	 
    	super.onUpdate(context, appWidgetManager, appWidgetIds); 	

    	synchronized(this)
    	{
    		Log.d(TAG, "onUpdate() start");
	    	for(int i = 0 ; i < appWidgetIds.length ; i ++) 
	    	{    		
	    		Log.d(TAG, "add widget id = ["+ String.valueOf(i) +"]=" + appWidgetIds[i]);	    		
	        	StockWidgetItem item = new StockWidgetItem();
	        	item.mAppWidgetId = appWidgetIds[i];	        	
	        	item.sym = "3041.TW";           	
	        	mItemsList.add(item);
	        	SetWidgetConfigAction(context,appWidgetManager,item);
	    	}
			//updateWidgetView(context,mItemsList);		    	
	    	Log.d(TAG, "onUpdate() end");
    	}    
    }    
    
    public void SetWidgetConfigAction(Context context, AppWidgetManager appWidgetManager, StockWidgetItem item)
    {   
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        Intent intent = new Intent(context,StockWidgetConfigure.class);        
        intent.putExtra(StockWidgetConfigure.ITEM_WIDGET_ID, item.mAppWidgetId );   
        PendingIntent pendingIntent = PendingIntent.getActivity(context,item.mAppWidgetId ,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.textViewName, pendingIntent);
        remoteViews.setOnClickPendingIntent(R.id.textViewPrice, pendingIntent);
        appWidgetManager.updateAppWidget(item.mAppWidgetId, remoteViews);
    }    

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub		
		if (intent.getAction().equals(StockWidgetConfigure.ACTION_CONFIG_DONE)) 
	    {
			String new_sym;
			boolean enabled;
			int ret_widget_id;
			Bundle extras = intent.getExtras();
			StockItem CurrItem;		
			ret_widget_id = extras.getInt(StockWidgetConfigure.ITEM_WIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);	
			new_sym = extras.getString(StockWidgetConfigure.ITEM_SYMB);	
			enabled = extras.getBoolean(StockWidgetConfigure.WIDGET_ENABLE);
			
			CurrItem = StockWidgetItem.FindItem(mItemsList, ret_widget_id);	
			Log.e(TAG, "onReceive() ACTION_CONFIG_DONE: widget mWidgetEnabled=" + 
					enabled + " id=" + ret_widget_id + " sym=" + CurrItem.sym);
			synchronized(this)
			{
				CurrItem.reset();
				CurrItem.sym = new_sym;
				updateWidget(context,(StockWidgetItem)CurrItem);
			}
			if(enabled)
			{
				startTimer(context);
			}
			else
			{
				stopTimer(context);				
			}
		}   		
		super.onReceive(context, intent);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		synchronized(this)
		{
			Log.d(TAG, "onDeleted() start");
	    	for(int i = 0 ; i < appWidgetIds.length ; i ++) 
	        {
	    		Log.d(TAG, "remove widget id = ["+ String.valueOf(i) +"]=" + appWidgetIds[i]);    		
	        	StockWidgetItem.RemoveItem(mItemsList,appWidgetIds[i]);
	    	}
	    	Log.d(TAG, "onDeleted() end");
		}
		// TODO Auto-generated method stub	
		super.onDeleted(context, appWidgetIds);		
	}
	
	@Override
	public void onDisabled(Context context) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onDisabled() start");
		stopTimer(context);		
		Log.d(TAG, "onDisabled() end");
		super.onDisabled(context);
		
	}
	
	@Override
    public void onEnabled(Context context) {					
		super.onEnabled(context);		
		// TODO Auto-generated method stub		
		Log.d(TAG, "onEnabled() start");	
		if(mItemsList == null)
		    mItemsList = new ArrayList<StockItem>();
		//Test(context);
		startTimer(context);		
		Log.d(TAG, "onEnabled() end");
	}

	public static void startTimer(final Context context)
	{
		mConfig.mUpdateEnable = true;
		if(mThreadRun)
			return;
		Log.d(TAG, "startTimer() start");	
		
		mThread = new Thread(){
			public void run(){
				while(mThreadRun){
					try {
						
						Thread.sleep(mConfig.update_period_second*1000);

						if(mItemsList.isEmpty())
							continue;
						
						List<StockItem> update_list;
						
						synchronized(this)
						{
							update_list = StockWidgetItem.CloneItemList(mItemsList);						
						}
						
						if(updateItemsInfo(context,update_list))
						{
							synchronized(this)
							{	
								updateAllWidget(context,mItemsList);
							}							
						}

					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		};
		mThreadRun = true;
		mThread.start();
		
		Log.d(TAG, "startTimer() end");	
	}
	
	public static void stopTimer(final Context context)
	{
		mConfig.mUpdateEnable = false;
		if(!mThreadRun)
			return;
		
		Log.d(TAG, "stopTimer() start");	
		
		mThreadRun = false;
		mThread.interrupt();

		try {
			mThread.join(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.d(TAG, "stopTimer() end");	
	}


	public static class StockUpdateService extends Service {
		@Override
		public void onStart(Intent intent, int startId) 
		{				
			Log.d(TAG, "StockUpdateService onStart start" + startId);		    
			Bundle bundle = intent.getExtras();
			
			StockWidgetItem item = new StockWidgetItem();
			item.mAppWidgetId = bundle.getInt(INTENT_ITEM_WIDGET_ID);
			item.sym = bundle.getString(INTENT_ITEM_SYMB);
			item.name = bundle.getString(INTENT_ITEM_NAME);
			item.price = bundle.getFloat(INTENT_ITEM_PRICE);
			item.change_percent = bundle.getFloat(INTENT_ITEM_CHANGE_PERCENT);
			item.change = bundle.getFloat(INTENT_ITEM_CHANGE);
				
			String str_price;
		    str_price = String.valueOf(item.price);
			
		    int ChangeTextColor = android.graphics.Color.BLACK;		
		    String strChangeText="";		    
		    String strChangePercentText="";
		    
			if(item.change_percent > 0)
			{
				strChangeText = "+";
				strChangePercentText = "+";
				ChangeTextColor = android.graphics.Color.RED;
			}
			else if(item.change_percent < 0)
			{
				ChangeTextColor = android.graphics.Color.GREEN;
			}
			strChangePercentText += String.valueOf(item.change_percent)+"%";
			strChangeText += String.valueOf(item.change);
			
			RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_layout);
			remoteViews.setTextViewText(R.id.textViewPrice,str_price);
			remoteViews.setTextViewText(R.id.textViewName,item.sym);	
			remoteViews.setTextColor(R.id.textViewChange,ChangeTextColor);
			remoteViews.setTextViewText(R.id.textViewChange,strChangeText);
			remoteViews.setTextColor(R.id.textViewChangeInPercent,ChangeTextColor);
			remoteViews.setTextViewText(R.id.textViewChangeInPercent,strChangePercentText);			
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(item.mAppWidgetId, remoteViews);
			
			Log.d(TAG, "StockUpdateService onStart end");	
		}
		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
	}  

	public static boolean updateItemsInfo(final Context context,List<StockItem> item_list)
	{			
		String str_error_msg = "";						
    	StockDatabase database = new StockDatabase();
		if(!database.UpdateItems(item_list))
		{
			str_error_msg = database.GetErrorMessage();
			Log.e(TAG, "UpdateItems failed:" + str_error_msg);
			return false;
		}
		return true;							
	}	
	
	public static void updateWidget(final Context context,StockWidgetItem item)
	{
		Log.d(TAG, "updateWidgetView:" + item.sym + "," + item.name + "," + item.price + "," + item.change_percent + "," +  item.change);	
    	Intent intent = new Intent(context, StockUpdateService.class);
    	intent.putExtra(INTENT_ITEM_WIDGET_ID, ((StockWidgetItem)item).mAppWidgetId);
		intent.putExtra(INTENT_ITEM_SYMB, item.sym);
		intent.putExtra(INTENT_ITEM_NAME, item.name);
		intent.putExtra(INTENT_ITEM_PRICE, item.price);
		intent.putExtra(INTENT_ITEM_CHANGE_PERCENT, item.change_percent);
		intent.putExtra(INTENT_ITEM_CHANGE, item.change);
		context.startService(intent);			
	}
	
	public static void updateAllWidget(final Context context,List<StockItem> item_list)
	{
		for(StockItem item:item_list){				
			updateWidget(context,(StockWidgetItem)item);
		}	
	}	
	
} 
